import { defineStore } from "pinia";
import { GetToken, RemoveToken, SetToken } from "../utils/storage";
import { Login, Register, Logout } from "../api/user";
import { ref } from "vue";

export const useUserStore = defineStore('user', () => { 
    const token = ref(GetToken() || '')
    const SetTokenPinia = (newToken) => { 
        token.value = newToken // 使用不同的参数名避免冲突
        SetToken(newToken)
    }
    

    
    // 其余代码保持不变...
    const RemoveTokenPinia = () => { 
        token.value = ''
        RemoveToken()
    }
    
    const LoginPinia = async (LoginForm) => { 
        try {
        const res = await Login(LoginForm)
            SetTokenPinia(res.data.token)
            return {success:true,data:res.data}
        } catch (error) { 
            return {success:false,data:error}
        }
    }

    const RegisterPinia = async (RegisterForm) => { 
        try {
            const res = await Register(RegisterForm)
            return {success:true,data:res}
        } catch (error) { 
            return {success:false,data:error}
        }
    }
    const LogoutPinia = async () => { 
        try {
            const res = await Logout()
            RemoveTokenPinia()
            return {success:true,data:res}
        } catch (error) { 
            return {success:false,data:error}
        }
    }
    return { token, SetTokenPinia, RemoveTokenPinia, LoginPinia, RegisterPinia, LogoutPinia }
})